package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysEmailConfig;
import com.ruoyi.system.domain.SysEmailLog;
import com.ruoyi.system.domain.SysUserEmail;
import com.ruoyi.system.mapper.SysEmailConfigMapper;
import com.ruoyi.system.mapper.SysEmailLogMapper;
import com.ruoyi.system.mapper.SysEmailAttachmentMapper;
import com.ruoyi.system.mapper.SysUserEmailMapper;
import com.ruoyi.system.service.ISysEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.core.io.FileSystemResource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysEmailAttachment;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 邮件服务实现类
 */
@Service
public class SysEmailServiceImpl implements ISysEmailService {
    private static final Logger log = LoggerFactory.getLogger(SysEmailServiceImpl.class);

    @Autowired
    private SysEmailConfigMapper emailConfigMapper;

    @Autowired
    private SysEmailLogMapper emailLogMapper;

    @Autowired
    private SysEmailAttachmentMapper emailAttachmentMapper;

    @Autowired
    private SysUserEmailMapper userEmailMapper;

    @Override
    public boolean sendSimpleMail(Long userId, String to, String subject, String content) {
        return sendFullMail(userId, to, null, null, subject, content, false, null, "0");
    }

    @Override
    public boolean sendHtmlMail(Long userId, String to, String subject, String content) {
        return sendFullMail(userId, to, null, null, subject, content, true, null, "0");
    }

    @Override
    public boolean sendAttachmentsMail(Long userId, String to, String subject, String content, List<File> files) {
        return sendFullMail(userId, to, null, null, subject, content, false, files, "0");
    }

    @Override
    public boolean sendImageMail(Long userId, String to, String subject, String content, List<File> imageFiles) {
        return sendFullMail(userId, to, null, null, subject, content, true, imageFiles, "0");
    }

    @Override
    @Transactional
    public boolean sendFullMail(Long userId, String to, String cc, String bcc, String subject, String content,
            boolean isHtml, List<File> files, String importance) {
        SysEmailLog emailLog = new SysEmailLog();
        try {
            // 获取默认邮件配置
            SysEmailConfig config = selectDefaultEmailConfig();
            if (config == null) {
                throw new RuntimeException("未配置邮件服务器信息");
            }

            // 获取用户默认邮箱
            SysUserEmail userEmail = selectDefaultUserEmail(userId);
            if (userEmail == null) {
                throw new RuntimeException("未配置发件人邮箱信息");
            }

            // 创建邮件日志
            emailLog.setUserId(userId);
            emailLog.setFromEmail(userEmail.getEmailAddress());
            emailLog.setFromName(userEmail.getEmailName());
            emailLog.setToEmail(to);
            emailLog.setCcEmail(cc);
            emailLog.setBccEmail(bcc);
            emailLog.setSubject(subject);
            emailLog.setContent(content);
            emailLog.setContentType(isHtml ? "html" : "text");
            emailLog.setImportance(importance);
            emailLog.setSendTime(DateUtils.getNowDate());

            // 发送邮件
            JavaMailSenderImpl mailSender = getMailSender(config);
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            
            // 设置发件人
            helper.setFrom(userEmail.getEmailAddress(), userEmail.getEmailName());
            
            // 设置收件人
            helper.setTo(to.split(";"));
            
            // 设置抄送
            if (StringUtils.isNotEmpty(cc)) {
                helper.setCc(cc.split(";"));
            }
            
            // 设置密送
            if (StringUtils.isNotEmpty(bcc)) {
                helper.setBcc(bcc.split(";"));
            }
            
            // 设置主题
            helper.setSubject(subject);
            
            // 设置内容
            helper.setText(content, isHtml);

            // 添加附件
            if (files != null && !files.isEmpty()) {
                for (File file : files) {
                    FileSystemResource resource = new FileSystemResource(file);
                    helper.addAttachment(file.getName(), resource);
                    
                    // 保存附件信息
                    SysEmailAttachment attachment = new SysEmailAttachment();
                    attachment.setLogId(emailLog.getLogId());
                    attachment.setFileName(file.getName());
                    attachment.setFilePath(file.getAbsolutePath());
                    attachment.setFileSize(file.length());
                    attachment.setFileType(getFileType(file.getName()));
                    attachment.setIsImage(isImageFile(file.getName()) ? "Y" : "N");
                    emailAttachmentMapper.insertSysEmailAttachment(attachment);
                }
            }

            // 发送邮件
            mailSender.send(message);
            emailLog.setSendStatus("0");
            
        } catch (Exception e) {
            emailLog.setSendStatus("1");
            emailLog.setErrorInfo(e.getMessage());
            log.error("发送邮件失败：", e);
            return false;
        } finally {
            // 保存日志
            emailLogMapper.insertSysEmailLog(emailLog);
        }
        
        return true;
    }

    /**
     * 获取文件类型
     */
    private String getFileType(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix.toLowerCase();
    }

    /**
     * 判断是否图片文件
     */
    private boolean isImageFile(String fileName) {
        String[] imageTypes = {"jpg", "jpeg", "png", "gif", "bmp"};
        String fileType = getFileType(fileName);
        for (String type : imageTypes) {
            if (type.equalsIgnoreCase(fileType)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取邮件发送器
     */
    private JavaMailSenderImpl getMailSender(SysEmailConfig config) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(config.getEmailHost());
        sender.setPort(config.getEmailPort());
        sender.setUsername(config.getEmailUsername());
        sender.setPassword(config.getEmailPassword());
        sender.setDefaultEncoding("UTF-8");
        
        // 配置SSL
        if ("Y".equals(config.getEmailSsl())) {
            sender.getJavaMailProperties().put("mail.smtp.ssl.enable", "true");
            sender.getJavaMailProperties().put("mail.smtp.ssl.trust", config.getEmailHost());
        }
        
        return sender;
    }

    @Override
    public SysEmailConfig selectSysEmailConfigById(Long configId) {
        return emailConfigMapper.selectSysEmailConfigById(configId);
    }

    @Override
    public List<SysEmailConfig> selectSysEmailConfigList(SysEmailConfig sysEmailConfig) {
        return emailConfigMapper.selectSysEmailConfigList(sysEmailConfig);
    }

    @Override
    public int insertSysEmailConfig(SysEmailConfig sysEmailConfig) {
        sysEmailConfig.setCreateTime(DateUtils.getNowDate());
        return emailConfigMapper.insertSysEmailConfig(sysEmailConfig);
    }

    @Override
    public int updateSysEmailConfig(SysEmailConfig sysEmailConfig) {
        sysEmailConfig.setUpdateTime(DateUtils.getNowDate());
        return emailConfigMapper.updateSysEmailConfig(sysEmailConfig);
    }

    @Override
    public int deleteSysEmailConfigById(Long configId) {
        return emailConfigMapper.deleteSysEmailConfigById(configId);
    }

    @Override
    public int deleteSysEmailConfigByIds(Long[] configIds) {
        return emailConfigMapper.deleteSysEmailConfigByIds(configIds);
    }

    @Override
    public SysEmailLog selectSysEmailLogById(Long logId) {
        SysEmailLog emailLog = emailLogMapper.selectSysEmailLogById(logId);
        if (emailLog != null) {
            // 查询附件列表
            List<SysEmailAttachment> attachments = emailAttachmentMapper.selectSysEmailAttachmentsByLogId(logId);
            emailLog.setAttachments(attachments);
        }
        return emailLog;
    }

    @Override
    public List<SysEmailLog> selectSysEmailLogList(SysEmailLog sysEmailLog) {
        List<SysEmailLog> list = emailLogMapper.selectSysEmailLogList(sysEmailLog);
        for (SysEmailLog log : list) {
            // 查询附件列表
            List<SysEmailAttachment> attachments = emailAttachmentMapper.selectSysEmailAttachmentsByLogId(log.getLogId());
            log.setAttachments(attachments);
        }
        return list;
    }

    @Override
    public int insertSysEmailLog(SysEmailLog sysEmailLog) {
        sysEmailLog.setCreateTime(DateUtils.getNowDate());
        return emailLogMapper.insertSysEmailLog(sysEmailLog);
    }

    @Override
    public int updateSysEmailLog(SysEmailLog sysEmailLog) {
        sysEmailLog.setUpdateTime(DateUtils.getNowDate());
        return emailLogMapper.updateSysEmailLog(sysEmailLog);
    }

    @Override
    @Transactional
    public int deleteSysEmailLogById(Long logId) {
        // 删除附件
        emailAttachmentMapper.deleteSysEmailAttachmentByLogId(logId);
        // 删除日志
        return emailLogMapper.deleteSysEmailLogById(logId);
    }

    @Override
    @Transactional
    public int deleteSysEmailLogByIds(Long[] logIds) {
        // 删除附件
        for (Long logId : logIds) {
            emailAttachmentMapper.deleteSysEmailAttachmentByLogId(logId);
        }
        // 删除日志
        return emailLogMapper.deleteSysEmailLogByIds(logIds);
    }

    @Override
    public SysEmailConfig selectDefaultEmailConfig() {
        SysEmailConfig config = new SysEmailConfig();
        config.setIsDefault("Y");
        config.setStatus("0");
        List<SysEmailConfig> list = emailConfigMapper.selectSysEmailConfigList(config);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public SysUserEmail selectDefaultUserEmail(Long userId) {
        return userEmailMapper.selectDefaultUserEmail(userId);
    }

    @Override
    public SysUserEmail selectSysUserEmailById(Long userEmailId) {
        return userEmailMapper.selectSysUserEmailById(userEmailId);
    }

    @Override
    public List<SysUserEmail> selectSysUserEmailList(SysUserEmail sysUserEmail) {
        return userEmailMapper.selectSysUserEmailList(sysUserEmail);
    }

    @Override
    public List<SysUserEmail> selectUserEmailList(Long userId) {
        return userEmailMapper.selectUserEmailList(userId);
    }

    @Override
    @Transactional
    public int insertSysUserEmail(SysUserEmail sysUserEmail) {
        sysUserEmail.setCreateTime(DateUtils.getNowDate());
        if ("Y".equals(sysUserEmail.getIsDefault())) {
            userEmailMapper.clearUserDefaultEmail(sysUserEmail.getUserId());
        }
        return userEmailMapper.insertSysUserEmail(sysUserEmail);
    }

    @Override
    @Transactional
    public int updateSysUserEmail(SysUserEmail sysUserEmail) {
        sysUserEmail.setUpdateTime(DateUtils.getNowDate());
        if ("Y".equals(sysUserEmail.getIsDefault())) {
            userEmailMapper.clearUserDefaultEmail(sysUserEmail.getUserId());
        }
        return userEmailMapper.updateSysUserEmail(sysUserEmail);
    }

    @Override
    public int deleteSysUserEmailById(Long userEmailId) {
        return userEmailMapper.deleteSysUserEmailById(userEmailId);
    }

    @Override
    public int deleteSysUserEmailByIds(Long[] userEmailIds) {
        return userEmailMapper.deleteSysUserEmailByIds(userEmailIds);
    }
} 